/**
 * Copyright 2011 AJG van Schie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.googlecode.julius.controller;

import java.util.List;
import java.util.Map;

import julius.utilities.CollectionHelper;

import org.joda.time.LocalDate;

import com.googlecode.julius.data.DataReaderApi;
import com.googlecode.julius.data.DataReaderApi.SprintContents;
import com.googlecode.julius.data.Status;
import com.googlecode.julius.utils.ParallelForEach.ProgressCallback;

public class ControllerImpl implements ControllerApi {

    class DayEntryImpl implements DayEntry {

        private final LocalDate day;
        private final Map<Status, Double> stateHours;

        public DayEntryImpl(final LocalDate day, final Map<Status, Double> stateHours) {
            this.day = day;
            this.stateHours = stateHours;
        }

        @Override
        public LocalDate day() {
            return day;
        }

        @Override
        public Double hours(final Status state) {
            return stateHours.get(state);
        }

    }

    private final DataReaderApi read;

    public ControllerImpl(final DataReaderApi read) {
        super();
        this.read = read;
    }

    @Override
    public List<Sprint> readSprints() {
        return read.readSprints();
    }

    @Override
    public List<DayEntry> readData(final Sprint sprint, final ProgressCallback c) {
        SprintContents contents = read.readSprintContents(sprint, c);
        List<DayEntry> entries = CollectionHelper.list();
        for (LocalDate day : sprint.daysInSprint()) {

            Map<Status, Double> stateHours = calculateHoursPerStateForDay(contents, day);

            entries.add(new DayEntryImpl(day, stateHours));
        }
        return entries;
    }

    private Map<Status, Double> calculateHoursPerStateForDay(final SprintContents contents, final LocalDate day) {
        Map<Status, Double> stateHours = CollectionHelper.map();
        for (Status state : Status.values()) {
            Double hours = contents.hours(day, state);
            stateHours.put(state, hours);
        }
        return stateHours;
    }

}
